package com.luck.emp.product.logic;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.luck.emp.common.SpProductNo;
import com.luck.emp.entity.EmpTProdAss;
import com.luck.emp.entity.EmpTProdAssId;
import com.luck.emp.entity.EmpTProdBase;
import com.luck.emp.entity.EmpTProdSale;
import com.luck.emp.entity.EmpTProdVend;
import com.luck.emp.entity.EmpTProdVendId;
import com.luck.emp.product.qry.ProductQry;
import com.luck.pf.common.entity.UserBean;
import com.luck.pf.framework.dao.BaseJdbcDao;
import com.luck.pf.framework.logic.BaseLogic;
import com.luck.pf.util.CriteriaUtil;
import com.luck.pf.util.DateUtil;

/**
 * 说明 Copyright: Copyright (c) 2011 深圳**科技
 * 
 * @author
 * 
 */
public class ProductLogic extends BaseLogic implements IProductLogic {
	private BaseJdbcDao jdbcDao;

	/**
	 * 查找分页信息
	 */
	public <T> T findProductPage(ProductQry qry, Class<T> cls) {
		Criteria criteria = baseDao.createCriteria(EmpTProdBase.class);
		CriteriaUtil.addFullLike(criteria, "productCode", qry.getProductCode());
		CriteriaUtil.addFullLike(criteria, "name", qry.getName());
		CriteriaUtil.addEq(criteria, "status", qry.getStatus());
		// 是否是组装商品
		CriteriaUtil.addEq(criteria, "isdiy", qry.getIsdiy());
		if(StringUtils.isNotBlank(qry.getVendorCode())){
			criteria.add(Restrictions.in("productCode", findProductCodesByVendorCode(qry.getVendorCode())));
		}
		CriteriaUtil.addEq(criteria, "prodKindId", qry.getKindId());
		Order order = Order.desc("productCode");
		criteria.addOrder(order);
		if(qry.getOrgId() != null)
			CriteriaUtil.addEq(criteria, "deptId", qry.getOrgId());
		else{
			criteria.createAlias("dept", "d");
			filterData(criteria, qry.getUserInfo(), "d", null);
		}
		if (cls.getName().equals("java.util.List")) {
			return (T) criteria.list();
		} else {
			return (T) baseDao.pagedQuery(criteria, qry.getPageNo(),
					qry.getPageSize());
		}
	}
	//根据供应商编码，得到此供应所有的商品列表
	public String[] findProductCodesByVendorCode(String vendorCode){
		List<EmpTProdVend> pv = super.baseDao.find(" FROM EmpTProdVend WHERE id.vendorCode=?", vendorCode);
		String[] strs = new String[pv.size()];
		for(int i=0; i < pv.size(); i ++){
			EmpTProdVend info = pv.get(i);
			strs[i] = info.getId().getProductCode();
		}
		return strs;
	}
	
	/**
	 * 保存
	 **/
	public String saveProduct(UserBean userBean, EmpTProdBase base)
			throws Exception {
		StringBuffer bf = new StringBuffer();
		String productCode = "";

		base.setModiUser(userBean.getUser());
		base.setModiDate(DateUtil.getDate());
		// 检查保存逻辑，为新建
		if (StringUtils.isBlank(base.getProductCode())) {
			if (StringUtils.isNotBlank(base.getProdBarcode())) {
				if (findProductByProdBarcode(userBean.getOrgId(), base.getProdBarcode()) != null)
					bf.append("此商品条码已经存在<br>");
			}
			if (StringUtils.isNotBlank(base.getSku())) {
				if (findProductBySku(userBean.getOrgId(), base.getSku()) != null)
					bf.append("此SKU码已经存在<br>");
			}
			if (StringUtils.isNotBlank(base.getVendorCode())) {
				if (findProductByVendorCode(userBean.getOrgId(), base.getVendorCode()) != null)
					bf.append("此供应商条码已经存在<br>");
			}
			if (StringUtils.isNotBlank(bf.toString()))
				throw new Exception(bf.toString());

			SpProductNo sp = new SpProductNo(this.jdbcDao.getJdbcTemplate());
			productCode = sp.execute(userBean.getDept().getDeptCode());
			base.setProductCode(productCode);
			base.setDeptId(userBean.getOrgId());
			base.setCreateUser(userBean.getUser());
			base.setCreateDate(DateUtil.getDate());

			EmpTProdSale sale = new EmpTProdSale();
			sale.setProductCode(productCode);
			sale.setIsBook("1");
			sale.setLowPrice(0.00);
			sale.setPrice(0.00);
			sale.setProfit(0.00);
			sale.setPurPrice(0.00);
			sale.setStdPrice(0.00);
			sale.setStockPrice(0.00);
			super.save(sale);
		} else {
			productCode = base.getProductCode();
			EmpTProdBase b = new EmpTProdBase();
			if (StringUtils.isNotBlank(base.getProdBarcode())) {
				b = findProductByProdBarcode(userBean.getOrgId(), base.getProdBarcode());
				if (b != null && !b.getProductCode().equals(productCode))
					bf.append("此商品条码已经存在<br>");
			}
			if (StringUtils.isNotBlank(base.getSku())) {
				b = findProductBySku(userBean.getOrgId(), base.getSku());
				if (b != null && !b.getProductCode().equals(productCode))
					bf.append("此SKU码已经存在<br>");
			}
			if (StringUtils.isNotBlank(base.getVendorCode())) {
				b = findProductByVendorCode(userBean.getOrgId(), base.getVendorCode());
				if (b != null && !b.getProductCode().equals(productCode))
					bf.append("此供应商条码已经存在<br>");
			}
			if (StringUtils.isNotBlank(bf.toString()))
				throw new Exception(bf.toString());

		}
		// base.setModiUser(userBean.getUser());
		// base.setModiDate(DateUtil.getDate());
		// 如果保存逻辑不通过则会在BF中增加提示信息，如不为空，则抛出错误提示。
		if (StringUtils.isBlank(bf.toString())) {
			super.save(base);
		} else
			throw new Exception(bf.toString());
		return bf.toString();
	}

	public String saveProductSale(UserBean userBean, EmpTProdSale sale)
			throws Exception {
		StringBuffer bf = new StringBuffer();

		// 如果保存逻辑不通过则会在BF中增加提示信息，如不为空，则抛出错误提示。
		if (StringUtils.isBlank(bf.toString())) {
			super.save(sale);
		} else
			throw new Exception(bf.toString());
		return bf.toString();
	}

	public List<EmpTProdVend> findProdVendRel(ProductQry qry) {
		Criteria criteria = baseDao.createCriteria(EmpTProdVend.class);
		CriteriaUtil.addEq(criteria, "id.productCode", qry.getProductCode());
		return criteria.list();
	}

	public String saveProdVendRel(String productCode, String[] vendorCodes)
			throws Exception {
		StringBuffer bf = new StringBuffer();
		super.bulkUpdate(
				"delete from EmpTProdVend t where t.id.productCode = ?",
				productCode);
		if (vendorCodes == null) {
			bf.append("商品必须存在一个供应商");
		}
		if (StringUtils.isBlank(bf.toString())) {
			for (String str : vendorCodes) {
				EmpTProdVend bean = new EmpTProdVend();
				EmpTProdVendId id = new EmpTProdVendId();
				id.setProductCode(productCode);
				id.setVendorCode(str);
				bean.setId(id);
				super.save(bean);
			}
		} else
			throw new Exception(bf.toString());
		return bf.toString();
	}

	public List findProdAssRel(String productCode) {
		Criteria criteria = baseDao.createCriteria(EmpTProdAss.class);
		CriteriaUtil.addEq(criteria, "id.productCode", productCode);
		return criteria.list();
	}

	public String saveProdAssRel(String productCode, String[] productCodeSubs,
			String[] qtys) throws Exception {
		StringBuffer bf = new StringBuffer();
		super.bulkUpdate(
				"delete from EmpTProdAss t where t.id.productCode = ?",
				productCode);
		EmpTProdBase base = super.get(EmpTProdBase.class, productCode);
		if (productCodeSubs == null) {
			if (base.getIsdiy().equals("1"))
				bf.append("组装商品必须存在一个内件商品");
		} else {
			try {
				for (int i = 0, len = productCodeSubs.length; i < len; i++) {
					EmpTProdAss bean = new EmpTProdAss();
					EmpTProdAssId id = new EmpTProdAssId();
					id.setProductCode(productCode);
					id.setProductCodeSub(productCodeSubs[i]);
					bean.setQty(Long.valueOf(qtys[i]));
					bean.setId(id);
					super.save(bean);
				}
			} catch (Exception e) {
				bf.append("内件商品不能重复");
			}
		}
		if (StringUtils.isBlank(bf.toString())) {
		} else
			throw new Exception(bf.toString());
		return bf.toString();
	}

	/**
	 * 删除
	 */
	public String deleteProduct(UserBean userBean, EmpTProdBase entity)
			throws Exception {
		StringBuffer bf = new StringBuffer();
		// 检查删除逻辑
		// 检查是否有组装商品内件
		int count = super.baseDao.count("  select count(*) from EmpTProdAss t where t.id.productCode = ?",entity.getProductCode());
		if (count > 0)
			bf.append("<br>此商品有内件组装商品，请先删除组装商品关系");
		// 检查是有出入库
		count = super.baseDao.count("  select count(*) from EmpTWhOrderD t where t.productCode = ?",entity.getProductCode());
		if (count > 0)
			bf.append("<br>此商品有出入库记录");
		// 如果删除逻辑不通过则会在BF中增加提示信息，如不为空，则抛出错误提示。
		if (StringUtils.isBlank(bf.toString())) {
			super.baseDao.delete(entity);
			super.baseDao.deleteById(EmpTProdSale.class,entity.getProductCode());
			//删除供应商关系
			List<EmpTProdVend> ls = super.baseDao.find(" FROM EmpTProdVend WHERE id.productCode=?",entity.getProdType());
			super.baseDao.getHibernateTemplate().deleteAll(ls);			
		} else
			throw new Exception(bf.toString());
		return bf.toString();
	}

	public Boolean checkExistProductCode(String productCode) {
		EmpTProdBase base = super.get(EmpTProdBase.class, productCode);
		if (base != null)
			return true;
		return false;
	}

	public EmpTProdBase findProductBySku(Long deptId, String SKU) {
		List<EmpTProdBase> ls = super.baseDao.find(
				" FROM EmpTProdBase WHERE sku=? and deptId=? ",new Object[]{SKU, deptId});
		if (ls != null && ls.size() > 0)
			return ls.get(0);
		else
			return null;
	}

	public EmpTProdBase findProductByProdBarcode(Long deptId, String prodBarcode) {
		List<EmpTProdBase> ls = super.baseDao.find(
				" FROM EmpTProdBase WHERE prodBarcode=? and deptId=? ",new Object[]{prodBarcode,deptId});
		if (ls != null && ls.size() > 0)
			return ls.get(0);
		else
			return null;
	}

	public EmpTProdBase findProductByVendorCode(Long deptId, String vendorCode) {
		List<EmpTProdBase> ls = super.baseDao.find(
				" FROM EmpTProdBase WHERE vendorCode=?  and deptId=? ",new Object[]{vendorCode, deptId});
		if (ls != null && ls.size() > 0)
			return ls.get(0);
		else
			return null;
	}
	public List<EmpTProdBase> findProductsByWhcode(String whCode){
		return null;
	}
	public BaseJdbcDao getJdbcDao() {
		return jdbcDao;
	}

	public void setJdbcDao(BaseJdbcDao jdbcDao) {
		this.jdbcDao = jdbcDao;
	}

}